/**
 * Created by jiangtao on 2017/6/16.
 */

const ejs = require('ejs'),
      path = require('path'),
      express = require("express"),
      bodyParser = require('body-parser'),
      compression = require('compression');

const mime = require("mime");

const app = express();

app.use(compression());

//模板引擎为ejs
app.engine('html', ejs.__express);

//模板后缀为html
app.set('view engine', 'html');

//模板引擎根路径
app.set('views', path.join(__dirname, '/app/views'));

const crossHeader = {
    "Access-Control-Allow-Origin": "*",
    "Access-Control-Allow-Headers": "Content-Type,Content-Length,Authorization,Accept,X-Requested-With",
    "Access-Control-Allow-Methods": "PUT,POST,GET,DELETE,OPTIONS",
    "X-Powered-By": "3.2.1"
};

//静态资源路径
app.use('/static', express.static('public',{
    setHeaders:function(res,path,stat) {
        for (let key in crossHeader) {
            res.header(key, crossHeader[key]);
        }
        res.header("Content-type",`${mime.getType(path)}; charset=UTF-8`);
        res.header("Cache-Control",`max-age=600`);
    }
}));


app.use(bodyParser.urlencoded({
    extended: true
}));

const serverPort = 8001;

app.listen(serverPort, () => {
    console.log("server listen to port:" + serverPort)
});


//跨域设置
app.all('*', (req, res, next) => {
    for (let key in crossHeader) {
        res.header(key, crossHeader[key]);
    }
    req.method === "OPTIONS" ? res.sendStatus(200) : next();
});

require('./app')(app);
